package edu.maplef.bookwild.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

import edu.maplef.bookwild.config.Config;
import edu.maplef.bookwild.config.Constants;
import edu.maplef.bookwild.schema.Base;

public class DataCache {

	private static final Logger log = Logger.getLogger(DataCache.class
			.getName());
	private static DataCache instance;
	private Cache cache;
	/**
	 * 缓存时间，默认从配置文件中读取，读取失败时设为3600s;
	 */
	private static long ttl = Long.parseLong(Config
			.getConfig(Constants.CACHE_TIMETOLIVE));

	@SuppressWarnings("unchecked")
	private DataCache(long ttl) {
		try {
			//创建生存期固定的数据缓存
			Map props = new HashMap();
			props.put(GCacheFactory.EXPIRATION_DELTA, ttl);
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			cache = cacheFactory.createCache(props);
		} catch (CacheException e) {
			log.severe("Error in creating the cache");
		}
	}

	public static synchronized DataCache getInstance() {
		if (instance == null) {
			instance = new DataCache(ttl);
		}
		return instance;
	}

	public static synchronized DataCache getInstance(long ttl) {
		if (instance == null) {
			instance = new DataCache(ttl);
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public void putInCache(String id, Base obj) {
		cache.put(id, obj);
	}

	public Base delInCache(String id) {
		return (Base) cache.remove(id);
	}

	public Base findInCache(String id) {
		if (cache.containsKey(id)) {
			return (Base) cache.get(id);
		} else {
			return null;
		}
	}
}